package com.zhongmai.yzfgrabanorder.fragment;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zhongmai.yzfgrabanorder.Adapter.AppealRecyclerViewAdapter;
import com.zhongmai.yzfgrabanorder.R;
import com.zhongmai.yzfgrabanorder.activity.MainActivity;
import com.zhongmai.yzfgrabanorder.activity.OrderInfoActivity;
import com.zhongmai.yzfgrabanorder.base.BaseFragment;
import com.zhongmai.yzfgrabanorder.bean.AppealOrderItemBean;
import com.zhongmai.yzfgrabanorder.utils.Constants;
import com.zhongmai.yzfgrabanorder.utils.EncryptUtils;
import com.zhongmai.yzfgrabanorder.utils.HttpXUtils;
import com.zhongmai.yzfgrabanorder.utils.PlayUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.zhongmai.yzfgrabanorder.netty_lib.netty.NettyClient.isConnect;
import static com.zhongmai.yzfgrabanorder.utils.Constants.user;

/**
 * 项目名称：YZFGrabAnOrder
 * 类描述：订单页
 * 创建人：Administrator
 * 创建时间：2020/9/17 15:30
 * 修改人：Administrator
 * 修改时间：2020/9/17 15:30
 * 修改备注：
 */
public class OrderFragment extends BaseFragment {

    @BindView(R.id.mSRL)
    SmartRefreshLayout mSRL;
    @BindView(R.id.mRV_all_appeal_orders)
    RecyclerView mRV_all_appeal_orders;

    private boolean refreshType = true;//刷新模式
    private int page = 1;
    private int oldListSize;
    private int newListSize;
    private int addListSize;
    private String viewType;
    private AppealRecyclerViewAdapter adapter;
    //    final LoadingDialog dialog = new LoadingDialog(getContext());

    public static List<AppealOrderItemBean> ordersList = new ArrayList<>();

    Handler fragmenthandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    refreshType = true;
                    page = 1;
                    parsingMovieListJson();
                    break;
                case 2:

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected int createSuccessView() {
        return R.layout.fragment_order;
    }

    @Override
    protected void changeLayout() {
        //        parsingMovieListJson();
        //        mSRL.autoRefresh();
    }

    @Override
    protected void loadingData() {

    }

    static boolean flag = true;

    @Override
    protected void switchFragemnt() {
        mTV_title.setText("订单");
        // 开启自动加载功能（非必须）
        //        mSRL.setEnableAutoLoadMore(true);
        if (flag || ordersList.size() <= 0) {
            flag = false;
            mSRL.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                    refreshLayout.getLayout().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshType = true;
                            page = 1;
                            logMag("加载page：" + page);
                            parsingMovieListJson();
                            refreshLayout.finishRefresh();
                            refreshLayout.resetNoMoreData();//setNoMoreData(false);
                            mSRL.setEnableRefresh(true);
                        }
                    }, 2000);
                }
            });
            mSRL.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                    refreshLayout.getLayout().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshType = false;
                            //                        if (page > 2) {
                            //                            showToast("暂无更多的数据啦");
                            //                            // 将不会再次触发加载更多事件
                            //                            refreshLayout.finishLoadMoreWithNoMoreData();
                            //                            return;
                            //                        }
                            parsingMovieListJson();
                            refreshLayout.setEnableLoadMore(true);
                            refreshLayout.finishLoadMore();
                        }
                    }, 2000);
                }
            });
            //触发自动刷新
            mSRL.autoRefresh();
        }
    }

    //判断页面是否正在显示
    protected boolean isVisible;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            logMag("orderfragment-------显示");
            isVisible = true;
//            if (waitRefresh) {//需要刷新
                refreshType = true;
                page = 1;
                //                parsingMovieListJson();
                //触发自动刷新
                mSRL.autoRefresh();
//            }
        } else {
            logMag("orderfragment-------不显示");
            isVisible = false;
        }
    }


    private void parsingMovieListJson() {
        // 从assets目录中获取json数据，在真实的项目开发中需要通过网络请求从服务器json数据
        //        String jsonData = BaseTools.getAssetsJson(this, "movie" + page + ".json");
        if (refreshType && ordersList != null) {
            ordersList.clear();
            oldListSize = 0;
        } else {
            oldListSize = ordersList.size();
        }
        RequestParams params = new RequestParams(Constants.Url + Constants.appealALL);
        try {
            params.addHeader("Authorization", user);
            JSONObject json = new JSONObject();

            json.put("pageSize", Constants.page_size);
            json.put("page", page);
            logMag("请求page：" + page);
            String def = EncryptUtils.encrypt(json.toString(), Constants.encrypt_key, Constants.encrypt_iv);
            String mdf = EncryptUtils.md5(def + Constants.encrypt_key).toUpperCase();
            params.addBodyParameter("def", def);
            params.addParameter("mdf", mdf);
        } catch (JSONException e1) {
            e1.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        HttpXUtils.xUtilsPostRequest(getActivity(), params, new HttpXUtils.MyCallback() {
            @Override
            public void myResult(String result) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("code");
                    if (code.equals("100000")) {
                        String jsonData = jsonObject.getString("data");
                        logMag("data111111------" + jsonData);
                        if (!"[]".equals(jsonData) && !"{}".equals(jsonData)) {
                            Constants.refresh = false;//不在刷新
                            Constants.waitOrder = false;
                            if (isVisible) {//订单列表页显示状态，直接刷新
                                if (waitRefresh) {
                                    waitRefresh = false;//关闭等待刷新状态
                                    PlayUtils.play(R.raw.sms_order);//提醒
                                }
                                Gson gson = new Gson();
                                List<AppealOrderItemBean> movieDataModelList = gson.fromJson(jsonData,
                                        new TypeToken<ArrayList<AppealOrderItemBean>>() {
                                        }.getType());
                                for (AppealOrderItemBean itemBean : movieDataModelList) {
                                    ordersList.add(itemBean);
                                    logMag("条目数：" + ordersList.size());
                                }
                                updateLayout();
                            } else {//不在订单列表页，
                                PlayUtils.play(R.raw.sms_order);
                            }
                            remindOrder();
                        } else {
                            if (ordersList.size() <= 0) {
                                Constants.waitOrder = true;
                                MainActivity activity = (MainActivity) getActivity();
                                activity.slidingTabLayoutRedDotGone();//关闭红点提示
                                mSRL.setBackground(getResources().getDrawable(R.mipmap.png_no_order));
                                openAutoRefresh();
                            } else {
                                showToast("无新增订单信息...");
                            }
                        }
                    } else {
                        String message = jsonObject.getString("message");
                        showToast(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String err) {
            }
        }, false);
    }

    boolean waitRefresh = false;

    /**
     * 提醒有新订单
     */
    private void remindOrder() {
        MainActivity activity = (MainActivity) getActivity();
        activity.slidingTabLayoutRedDotShow();
//        waitRefresh = true;
    }


    /**
     * 轮训请求订单
     */
    private void openAutoRefresh() {
        if (!isConnect) {
            Constants.waitOrder = false;
            return;
        }
        Constants.refresh = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    waitRefresh = true;//等待订单状态
                    Thread.sleep(Constants.refreshTime);
                    Message message = new Message();
                    message.what = 1;
                    fragmenthandler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void updateLayout() {
        mSRL.setBackground(getResources().getDrawable(R.color.CS_black_2_percent));
        newListSize = ordersList.size();
        addListSize = newListSize - oldListSize;
        if (refreshType) {
            // 设置RecyclerView样式为竖直线性布局
            mRV_all_appeal_orders.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,
                    false));
            adapter = new AppealRecyclerViewAdapter(getContext(), ordersList);
            // 设置分割线
            //            mRV_all_appeal_orders.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager
            //            .VERTICAL));
            mRV_all_appeal_orders.setAdapter(adapter);
        } else {
            adapter.notifyItemRangeInserted(ordersList.size() - addListSize, ordersList.size());
            adapter.notifyItemRangeChanged(ordersList.size() - addListSize, ordersList.size());
        }

        page++;

        mRV_all_appeal_orders.setVisibility(View.VISIBLE);
        // dialog.dismiss();
        // item条目的点击事件回调
        adapter.setItemClikListener(new AppealRecyclerViewAdapter.OnItemClikListener() {
            // 短按点击事件回调
            @Override
            public void onItemClik(View view, int position) {
                getOrderInfo(ordersList.get(position).getOrderId());
            }

            // 长按点击事件回调
            @Override
            public void onItemLongClik(View view, int position) {

            }
        });
    }

    private void getOrderInfo(String orderId) {
        RequestParams params = new RequestParams(Constants.Url + Constants.orderInfo);
        try {
            params.addHeader("Authorization", user);
            JSONObject json = new JSONObject();

            json.put("orderId", orderId);
            String def = EncryptUtils.encrypt(json.toString(), Constants.encrypt_key, Constants.encrypt_iv);
            String mdf = EncryptUtils.md5(def + Constants.encrypt_key).toUpperCase();
            params.addBodyParameter("def", def);
            params.addParameter("mdf", mdf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpXUtils.xUtilsPostRequest(getActivity(), params, new HttpXUtils.MyCallback() {
            @Override
            public void myResult(String result) {
                logMag("------------" + result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("code");
                    if (code.equals("100000")) {
                        String data = jsonObject.getString("data");
                        if (!data.equals("{}")) {
                            Intent intent = new Intent(OrderFragment.this.getActivity(), OrderInfoActivity.class);
                            Bundle bundle = new Bundle();
                            //传输的内容仍然是键值对的形式
                            bundle.putString("order", data);//回发的消息,hello world from
                            // secondActivity!
                            intent.putExtras(bundle);
                            getActivity().startActivityForResult(intent, 1);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String err) {

            }
        }, true);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void againLoad() {
        logMag("加载切换page：");
    }


    public void refreshList() {
        logMag("刷新界面...");
        mSRL.autoRefresh();
    }
}
